import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api/user.api'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    token: localStorage.getItem('token') || null,
    
    // 用户列表（管理员功能）
    users: [],
    usersPagination: {
      total: 0,
      page: 1,
      limit: 10,
      totalPages: 0
    },
    
    // 加载状态
    loading: false,
    userListLoading: false,
    
    // 角色选项
    roleOptions: [
      { label: '管理员', value: 'admin' },
      { label: '医生', value: 'doctor' },
      { label: '护士', value: 'nurse' },
      { label: '普通用户', value: 'user' }
    ]
  }),

  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token && !!state.userInfo,
    
    // 用户角色
    userRole: (state) => state.userInfo?.role || null,
    
    // 是否为管理员
    isAdmin: (state) => state.userInfo?.role === 'admin',
    
    // 是否为医生
    isDoctor: (state) => state.userInfo?.role === 'doctor',
    
    // 是否为护士
    isNurse: (state) => state.userInfo?.role === 'nurse',
    
    // 用户显示名称
    displayName: (state) => state.userInfo?.fullName || state.userInfo?.username || '未知用户'
  },

  actions: {
    /**
     * 用户登录
     * @param {Object} loginData - 登录数据
     */
    async login(loginData) {
      try {
        this.loading = true
        const response = await userApi.login(loginData)
        
        if (response.success) {
          const { user, token } = response.data
          
          // 保存用户信息和token
          this.userInfo = user
          this.token = token
          
          // 持久化存储
          localStorage.setItem('token', token)
          localStorage.setItem('userInfo', JSON.stringify(user))
          
          ElMessage.success('登录成功')
          return response
        }
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 用户登出
     */
    logout() {
      this.userInfo = null
      this.token = null
      this.users = []
      
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },

    /**
     * 获取当前用户信息
     */
    async getCurrentUser() {
      try {
        this.loading = true
        const response = await userApi.getCurrentUser()
        
        if (response.success) {
          this.userInfo = response.data
          localStorage.setItem('userInfo', JSON.stringify(response.data))
          return response.data
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果获取用户信息失败，可能是token过期，清除登录状态
        this.logout()
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 修改密码
     * @param {Object} passwordData - 密码数据
     */
    async changePassword(passwordData) {
      try {
        this.loading = true
        const response = await userApi.changePassword(passwordData)
        
        if (response.success) {
          ElMessage.success('密码修改成功')
          return response
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 获取用户列表（管理员功能）
     * @param {Object} params - 查询参数
     */
    async getUsers(params = {}) {
      try {
        this.userListLoading = true
        const response = await userApi.fetchUsers(params)
        
        if (response.success) {
          this.users = response.data.users
          this.usersPagination = response.data.pagination
          return response.data
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
        throw error
      } finally {
        this.userListLoading = false
      }
    },

    /**
     * 创建用户（管理员功能）
     * @param {Object} userData - 用户数据
     */
    async createUser(userData) {
      try {
        this.loading = true
        const response = await userApi.createUser(userData)
        
        if (response.success) {
          ElMessage.success('用户创建成功')
          // 刷新用户列表
          await this.getUsers({ page: this.usersPagination.page, limit: this.usersPagination.limit })
          return response.data
        }
      } catch (error) {
        console.error('创建用户失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 更新用户（管理员功能）
     * @param {number} id - 用户ID
     * @param {Object} userData - 更新数据
     */
    async updateUser(id, userData) {
      try {
        this.loading = true
        const response = await userApi.updateUser(id, userData)
        
        if (response.success) {
          ElMessage.success('用户信息更新成功')
          // 刷新用户列表
          await this.getUsers({ page: this.usersPagination.page, limit: this.usersPagination.limit })
          return response.data
        }
      } catch (error) {
        console.error('更新用户失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 删除用户（管理员功能）
     * @param {number} id - 用户ID
     */
    async deleteUser(id) {
      try {
        this.loading = true
        const response = await userApi.deleteUser(id)
        
        if (response.success) {
          ElMessage.success('用户删除成功')
          // 刷新用户列表
          await this.getUsers({ page: this.usersPagination.page, limit: this.usersPagination.limit })
          return response
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 根据ID获取用户信息（管理员功能）
     * @param {number} id - 用户ID
     */
    async getUserById(id) {
      try {
        this.loading = true
        const response = await userApi.fetchUserById(id)
        
        if (response.success) {
          return response.data
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 初始化用户状态（从本地存储恢复）
     */
    initializeAuth() {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')
      
      if (token && userInfo) {
        this.token = token
        try {
          this.userInfo = JSON.parse(userInfo)
        } catch (error) {
          console.error('解析用户信息失败:', error)
          this.logout()
        }
      }
    }
  }
})